package org.mms.service.impl;

import org.mms.exception.BusinessException;
import org.mms.pojo.entity.News;
import org.mms.pojo.request.NewsRequest;
import org.mms.repository.NewsRepository;
import org.mms.service.NewsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class NewsServiceImpl implements NewsService {
    @Autowired
    private NewsRepository newsRepository;

    @Override
    public List<News> list() {
        return newsRepository.findAll();
    }

    @Override
    public News getById(Long id) {
        return newsRepository.findById(id)
                .orElseThrow(() -> new BusinessException("新闻不存在"));
    }

    @Override
    public News create(String title, String content, String coverUrl) {
        News news = new News();
        news.setTitle(title);
        news.setContent(content);
        news.setCoverUrl(coverUrl);
        return newsRepository.save(news);
    }

    @Override
    public News update(Long id, String title, String content, String coverUrl) {
        News news = newsRepository.findById(id)
                .orElseThrow(() -> new BusinessException("新闻不存在"));
        news.setTitle(title);
        news.setContent(content);
        news.setCoverUrl(coverUrl);
        return newsRepository.save(news);
    }

    @Override
    public void delete(Long id) {
        newsRepository.deleteById(id);
    }

    @Override
    public List<News> search(String keyword) {
        return newsRepository.findByTitleContainingIgnoreCase(keyword);
    }
}